<template>
    <div>
        <Card>
            <Row>
                <i-col span="3">
                    <div class="dictionary-tree">
                        <Tree class="tree-list" :data="dictionaryTree" @on-select-change="getItemTableLIst"></Tree>
                    </div>
                </i-col>
                <i-col span="21">
                    <global-tables @handleAllSelect="handleAllSelect" :list="list" :loading="loading" :columns="columns" :isPage="true">
                        <Form :model="formItem" :label-width="80">
                            <div class="table-top-wrap">
                                <div>
                                    <Button v-if="isAddBtn" class="features-btn" @click="handleBtnClick(null,'add')">
                                        <Icon type="md-add" size="18" />新建
                                    </Button>
                                    <Button v-if="isDeleteBtn" class="features-btn btn-auto-m" @click="handleBtnClick(null,'delete')">
                                        <Icon class="btn btn-auto-m" type="md-trash" size="18" />删除
                                    </Button>
                                    <Button v-if="isProhibit" class="features-btn btn-auto-m" @click="handleBtnClick(null,'off')">
                                        <Icon type="ios-lock-outline" size="17" />停用
                                    </Button>
                                    <Button v-if="isProhibit" class="features-btn btn-auto-m" @click="handleBtnClick(null,'on')">
                                        <Icon type="ios-unlock-outline" size="17" />启用
                                    </Button>
                                </div>
                                <div class="table-top-wrap-bottom">
                                    <div>
                                        <input type="text" class="style-input" @keyup.enter="handleSearch" v-model="search.keyword" placeholder="请输入名称">
                                        <i-input style="display:none"></i-input>
                                    </div>
                                    <div>
                                        <Button icon="ios-search" class="search-btn" @click="handleSearch">搜索</Button>
                                    </div>
                                </div>
                            </div>
                        </Form>
                    </global-tables>
                </i-col>
            </Row>
            <div>
                <Modal :mask-closable="false" v-model="isModal" :title="ModalTitle">
                    <div v-if="isModal">
                        <Form ref="formItem" :model="formItem" :rules="ruleValidate" :label-width="100">
                            <Row>
                                <i-col :lg="{ span: 12}">
                                    <FormItem label="分类名称" prop="CName">
                                        <i-input v-model="formItem.CName" placeholder="请输入分类名称"></i-input>
                                    </FormItem>
                                </i-col>
                                <i-col :lg="{ span: 24}">
                                    <FormItem label="是否为顶级">
                                        <i-switch v-model="isSwitch" @on-change="handleSwitch">
                                            <span slot="open">是</span>
                                            <span slot="close">否</span>
                                        </i-switch>
                                    </FormItem>
                                </i-col>
                                <i-col :lg="{ span: 15}" v-if="!isSwitch">
                                    <FormItem label="商品分类" prop="ParentID">
                                        <Select v-model="formItem.ParentID" style="width:200px">
                                            <Option v-for="item in formItem.dictionaryList" :value="item.ID + ''" :key="item.ID">{{ item.CName }}</Option>
                                        </Select>
                                    </FormItem>
                                </i-col>
                            </Row>
                        </Form>
                    </div>
                    <div slot="footer">
                        <Button size="large" @click="handleClose">取消</Button>
                        <Button type="primary" size="large" @click="handleSubmit('formItem')">确定</Button>
                    </div>
                </Modal>
            </div>
        </Card>
    </div>
</template>

<script>
/**
 * 商品分类
 */
import { cyclicRouting } from "@/util";
import { getModulePermission } from "@/api/user";
import {
    getCategories,
    getTablesList,
    addTablesItem,
    deleteItem,
    setDisableEnable,
    getItemInfo
} from "./service";
import GlobalTables from "@/components/GlobalTables";
export default {
    name: "ProductsCagetory",
    components: {
        GlobalTables
    },
    data() {
        return {
            total: 0,
            itemId: 0,
            ModalTitle: "新建商品分类",
            isModal: false,
            allSelectArr: null,
            loading: true,
            isSwitch: false,
            isAddBtn: false,
            isEdit: false,
            isProhibit: false,
            isDeleteBtn: false,
            disabledGroup: "true",
            search: {
                keyword: "",
                parentid: ""
            },
            ruleValidate: this.initRuleValidate(),
            list: [],
            dictionaryTree: [],
            formItem: {
                CName: "",
                ParentID: "",
                dictionaryList: []
            },
            columns: [
                {
                    type: "selection",
                    width: 60,
                    align: "center"
                },
                {
                    title: "ID",
                    key: "ID"
                },
                {
                    title: "分类名称",
                    key: "CName"
                },
                {
                    title: "状态",
                    render: (h, params) => {
                        const { Isactivity } = params.row;
                        if (Isactivity) {
                            return h("div", [
                                h("Badge", {
                                    props: {
                                        status: "processing",
                                        text: "正常"
                                    }
                                })
                            ]);
                        } else {
                            return h("div", [
                                h("Badge", {
                                    props: {
                                        status: "error",
                                        text: "停用"
                                    }
                                })
                            ]);
                        }
                    }
                },
                {
                    title: "操作",
                    width: 100,
                    align: "center",
                    render: (h, params) => {
                        const { isEdit } = this;
                        return h("div", [
                            isEdit &&
                                h(
                                    "Button",
                                    {
                                        props: {
                                            type: "primary",
                                            size: "small"
                                        },
                                        style: {
                                            background: "#5ab1ef",
                                            border: "none",
                                            marginRight: "5px"
                                        },
                                        on: {
                                            click: () => {
                                                this.handleBtnClick(
                                                    params.row,
                                                    "edit"
                                                );
                                            }
                                        }
                                    },
                                    "修改"
                                )
                        ]);
                    }
                }
            ]
        };
    },
    mounted() {
        /* 获取菜单的id */
        cyclicRouting(
            JSON.parse(sessionStorage.getItem("user")).menuList,
            this.$route,
            id => {
                /* 按钮权限请求 */
                getModulePermission({
                    roleid: JSON.parse(sessionStorage.getItem("user")).roleid,
                    moduleid: id
                }).then(res => {
                    /* 按钮权限赋值 */
                    for (let item in res.data) {
                        if (res.data[item].name == "add") {
                            this.isAddBtn = true;
                        } else if (res.data[item].name == "delete") {
                            this.isDeleteBtn = true;
                        } else if (res.data[item].name == "onoff") {
                            this.isProhibit = true;
                        } else if (res.data[item].name == "edit") {
                            this.isEdit = true;
                        }
                    }
                    getCategories().then(res => {
                        this.changKey(res.data);
                        this.getTablesListData();
                    });
                });
            }
        );
    },
    methods: {
        /* 复选框选中 */
        handleAllSelect(list) {
            let arr = [];
            for (let item in list) {
                arr.push(list[item].ID);
                arr.join(",");
            }
            arr = arr.join(",");
            this.allSelectArr = arr;
        },
        /* 表格查询 */
        handleSearch() {
            this.loading = true;
            this.getTablesListData();
        },
        /* 关闭对话框 */
        handleClose() {
            this.isModal = false;
        },
        /* 是否为顶级分类 */
        handleSwitch(e) {
            if (e) {
                this.ParentID = 1;
            }
        },
        /* 对话框提交 */
        handleSubmit(name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    const { formItem, isSwitch } = this;
                    let data = {
                        ID: this.itemId,
                        CName: formItem.CName,
                        ParentID: isSwitch ? 0 : formItem.ParentID
                    };
                    addTablesItem(data).then(res => {
                        if (res.state == "success") {
                            this.$Message.success("操作成功");
                            this.loading = true;
                            this.handleClose();
                            this.search.keyword = "";
                            getCategories().then(res => {
                                this.changKey(res.data);
                                this.getTablesListData();
                            });
                        } else {
                            this.$Message.error(res.message);
                        }
                    });
                }
            });
        },
        /* 表格数据请求 */
        getTablesListData() {
            const data = this.search;
            getTablesList(data).then(res => {
                this.list = res.data.rows;
                this.loading = false;
                this.total = res.data.records;
            });
        },
        /* 左侧树点击 */
        getItemTableLIst(e) {
            this.search.parentid = e[0].value;
            this.search.keyword = "";
            this.formItem.ParentID = e[0].value + "";
            this.getTablesListData();
        },
        /* 更改数据结构 */
        changKey(list) {
            list.forEach(item => {
                item.title = item.label;
                item.expand = true;
                if (item.children && Array.isArray(item.children)) {
                    this.changKey(item.children);
                }
            });
            this.dictionaryTree = list;
        },
        /* 按钮点击 */
        handleBtnClick(item, type) {
            if (type == "edit" || type == "add") {
                this.ModalTitle = "新建分类";
                this.isSwitch = false;
                this.formItem.CName = "";
                this.formItem.dictionaryList = [];
                this.isModal = true;
                getTablesList().then(res => {
                    this.formItem.dictionaryList = res.data.rows;
                });
                if (type == "edit") {
                    this.ModalTitle = "修改分类";
                    getItemInfo({
                        keyValue: item.ID
                    }).then(res => {
                        this.itemId = item.ID;
                        this.formItem = {
                            ...this.formItem,
                            ...res.data,
                            ParentID: res.data.ParentID + ""
                        };
                        if (res.data.ParentID == 0) {
                            this.isSwitch = true;
                        }
                    });
                }
            } else if (type === "delete") {
                if (this.allSelectArr) {
                    this.$Modal.confirm({
                        title: `你确定要删除吗`,
                        onOk: () => {
                            deleteItem({
                                keyValue: this.allSelectArr
                            }).then(res => {
                                if (res.state == "success") {
                                    this.$Message.success(res.message);
                                    this.allSelectArr = "";
                                } else {
                                    this.$Message.error(res.message);
                                }
                                getCategories().then(res => {
                                    this.changKey(res.data);
                                    this.getTablesListData();
                                });
                            });
                        },
                        onCancel: () => {
                            this.$Message.info("取消成功");
                        }
                    });
                } else {
                    this.$Message.error("请先选择需要操作的记录");
                }
            } else if (type === "off" || type === "on") {
                let title = "";
                if (type === "off") {
                    title = "停用";
                } else {
                    title = "启用";
                }
                if (this.allSelectArr) {
                    this.$Modal.confirm({
                        title: `你确定要${title}吗`,
                        onOk: () => {
                            setDisableEnable({
                                keyValue: this.allSelectArr,
                                value: type === "off" ? 0 : 1
                            }).then(res => {
                                if (res.state == "success") {
                                    this.$Message.success(res.message);
                                    this.allSelectArr = "";
                                } else {
                                    this.$Message.error(res.message);
                                }
                                this.getTablesListData();
                            });
                        },
                        onCancel: () => {
                            this.$Message.info("取消成功");
                        }
                    });
                } else {
                    this.$Message.error("请先选择需要操作的记录");
                }
            }
        },
        /* 表单校验 */
        initRuleValidate() {
            return {
                CName: [
                    {
                        required: true,
                        message: "请输入分类名称",
                        trigger: "change"
                    }
                ],
                ParentID: [
                    {
                        required: true,
                        message: "请选择商品分类",
                        trigger: "change"
                    }
                ]
            };
        }
    }
};
</script>


<style lang="less" scoped>
.tree-wrap {
    position: relative;
    span {
        position: absolute;
        top: 0;
        left: -35px;
    }
    span:after {
        content: "*";
        position: absolute;
        display: block;
        width: 10px;
        height: 10px;
        color: red;
        font-size: 15px;
        top: 4px;
        left: -11px;
    }
}
.dictionary-tree {
    padding-top: 2px;
    height: 745px;
    overflow-x: auto;
}
</style>
